package com.example.msai.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Data
@Builder
@AllArgsConstructor

public class DeepSeekClient {
    private final String apiKey;
    private final RestTemplate restTemplate;

    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";



    public String reply(String prompt) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        // 根据DeepSeek API文档构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", prompt);
        requestBody.put("messages", Arrays.asList(message));

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<Map> response = restTemplate.postForEntity(API_URL, entity, Map.class);

        // 解析响应，根据实际API响应结构调整

        // 将响应体转换为 JSON 字符串并解析
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(response.getBody());

        JsonNode rootNode = objectMapper.readTree(jsonResponse);

    // 获取 content 字段
        String content = rootNode.path("choices")
                .get(0)
                .path("message")
                .path("content")
                .asText();

        return content;
    }


}
